<?php
//用户的添加等操作
/**
 * 用户注册
 * @return string
 */
function register(){
    $arr = $_POST;
    $arr['password'] = md5($_POST['password']);
    $arr['regTime'] = time();
    $uploadFile = uploadFile();

    if ($uploadFile && is_array($uploadFile)){
        $arr['face'] = $uploadFile[0]['name'];
    }else{
        return '注册失败';
    }

    if (insert('imooc_user',$arr)){
        $msg = '注册成功！<br><meta http-equiv="refresh" content="3;url=login.php">';
    }else{
        $filename = 'uploads/'.$uploadFile[0]['name'];
        if (file_exists($filename)){
            unlink($filename);
        }
        $msg = '注册失败！<br><a href="register.php">重新注册</a>|<a href="index.php">查看首页</a>';
    }
    return $msg;
}

/**
 * 用户登录
 * @return string
 */
function login(){
    $username = $_POST['username'];
    $username = mysql_escape_string($username);# 转义一个字符串用于 mysql_query
    $password = md5(isset($_POST['password']) ? $_POST['password'] : 123456);
    $sql = "select * from imooc_user where username = '{$username}' and password = '{$password}'";
    $row = fetchOne($sql);
    if ($row){
        $_SESSION['loginFlag'] = $row['id'];
        $_SESSION['username'] = $row['username'];
        $msg = "登录成功！<br><meta http-equiv='Refresh' content='3;url=index.php'>";
    }else{
        $msg = "登录失败！<a href='login.php'>重新登录</a>";
    }
    return $msg;
}

/**
 * 注销登录
 */
function userOut(){
    $_SESSION = array();
    if (isset($_COOKIE[session_name()])){
        setcookie(session_name(),'',time()-1);
    }

    session_destroy();
    header('location:index.php');
}
